'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 离开战斗
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var copyRecordModel = require('../../../models/copyRecordModel');
var fightRewardUtil = require('../../../util/fightRewardUtil');
var roleService = require('../../../services/roleService');
var rewardService = require('../../../services/rewardService');
var copyService = require('../../../services/copyService');
var activityService = require('../../../services/activityService');
var PlayerManager = require('../../../libs/playerManager');
var copyRewardService = require('../../../services/copyRewardService');
var taskService = require('../../../services/taskService');
var actType = require('../../../consts/activityType.js');
var copyConf = require('../../../config/copyConf');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 离开副本
 * 需要上传的数据:
 * 1.已经拆除的建筑
 * 2.已经打过的经济类的建筑
 * 3.要统计的数据
 */
Handler.prototype.exit = function (msg, session, next) {
    var role_id = session.uid;
    var record_id = msg.record_id;
    var damage_build_list = msg.damage_build_list || [];
    var data = msg.data || {};
    if (!record_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }
    // jshint maxstatements:100
    var copy_record_model;
    var player_manager = new PlayerManager(role_id);
    var reward_list = [];
    var progress = 0;
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                copyRecordModel.getRecordByAtkRoleId(role_id, record_id, cb);
            },
            function (model, cb) {
                copy_record_model = model;
                if (!copy_record_model) {
                    return next(null, {
                        code: Code.COPY_RECORD_NOT_EXIST
                    });
                }

                if (copy_record_model.getStar() !== undefined) {
                    return next(null, {
                        code: Code.COPY_HAVE_PASS
                    });
                }

                player_manager.getModel(
                    ['role', 'copy', 'bag', 'soldier', 'build', 'task', 'daily_task', 'achieve', 'sevenDayActivity', 'accrued'],
                    cb);
            },
            function (cb) {
                var copy_model = player_manager.copy;
                var role_model = player_manager.role;

                // 副本的星级
                var star = 0;
                var condition_list = _getStarProgress(copy_record_model, damage_build_list, data);
                _.some(condition_list, function (condition) {
                    if (condition.need && !condition.is_pass) {
                        star = 0;
                        return true;
                    }
                    if (condition.is_pass) {
                        star++;
                    }
                });

                var copy_id = copy_record_model.copy_id;

                // 判断这个副本的前置副本是否已经通关
                var copy_conf = copyConf.getCopyConf(copy_id);
                if (!copy_conf) {
                    return next(null, {
                        code: Code.COPY_NOT_EXIST
                    });
                }

                // 扣除体力
                var sp_cost = 0;
                if (star > 0) {
                    sp_cost = copy_conf.sp_cost;

                    if (copy_conf.difficulty == 2) {
                        // 判断精英副本次数
                        if (!copy_model.addHardCarbonTimes(copy_id)) {
                            return next(null, {
                                code: Code.COPY_HARD_FIGHT_TIMES_EXCEEDED
                            });
                        }
                    }
                } else {
                    sp_cost = copy_conf.lose_sp_cost;
                }
                if (!roleService.subEnergy(player_manager, moduleType.MDL_COPY, operationType.OPR_COPY_FIGHT, sp_cost)) {
                    return next(null, {
                        code: Code.USER_SP_NOT_ENOUGH
                    });
                }

                // 进度
                progress = _getEconomyBuildProgress(copy_record_model, damage_build_list);

                // 设置副本的奖励数据
                copy_record_model.setStar(star);
                copy_record_model.setProgress(progress);

                // 给用户添加副本宝箱奖励
                if (!!copy_record_model.canReward()) {
                    var first_reward_list = [];
                    var copy_info = copy_model.getCopy(copy_id);
                    if (!copy_info || copy_info.star < 1) {
                        first_reward_list = copyRewardService.getFirstRewardList(role_model.getJob(), copy_id);
                        rewardService.addRewardListToRole(player_manager, first_reward_list, moduleType.MDL_COPY, operationType.OPR_COPY_FIRST_REWARD);
                    }

                    var random_reward_list = copyRewardService.getRandomRewardList(role_model.getJob(), copy_id);
                    rewardService.addRewardListToRole(player_manager, random_reward_list, moduleType.MDL_COPY, operationType.OPR_COPY_FIGHT);

                    var fix_reward_list = copyRewardService.getFixRewardList(role_model.getJob(), copy_id);
                    rewardService.addRewardListToRole(player_manager, fix_reward_list, random_reward_list, moduleType.MDL_COPY, operationType.OPR_COPY_FIGHT);

                    reward_list = _.union(random_reward_list, fix_reward_list, first_reward_list);

                    copy_record_model.setReward();
                }

                // 保存星数
                copyService.passCopy(player_manager, copy_id, star);

                // 增加开服七天活动红点
                activityService.push(role_id, actType.COPY_STAR, player_manager);

                var lost_soldier_list = data.lost_soldier_list;
                if (!!lost_soldier_list) {
                    _.each(lost_soldier_list, function (soldier_item) {
                        player_manager.soldier.subProductedSoldierNum(soldier_item.soldier_type, soldier_item.num);
                    });
                }

                // 统计当前副本总星数
                var copy_list = copy_model.copy_list;
                var total_star = 0;
                _.each(copy_list, function (copy_item) {
                    total_star += copy_item.star;
                });

                if (role_model.total_copy_star_num < total_star) {
                    role_model.setCopyTotalStar(total_star);
                }

                // 副本统计
                taskService.addPassCopyNum(player_manager);
                copy_record_model.save();
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    def_name: copy_record_model.getDefName(),
                    add_cup: 0,
                    star: copy_record_model.getStar(),
                    progress: copy_record_model.getProgress(),
                    reward_list: reward_list
                }
            });
        }
    );
};

/**
 * 获取毁坏的经济类建筑能拿到的资源
 */
var _getEconomyBuildProgress = function (copy_record_model, damage_build_list) {
    return fightRewardUtil.getDamageProgress(copy_record_model, damage_build_list);
};

/**
 * 获取星级
 * @param  {[type]} copy_record_model  [description]
 * @param  {[type]} damage_build_list [description]
 * @return {[type]}                    [description]
 */
var _getStarProgress = function (copy_record_model, damage_build_list, data) {
    return copyService.getStarProgress(copy_record_model, damage_build_list, data);
};
